<template>
  <div class="book-borrow-system">
    <!-- 主体内容区 -->
    <div class="main-content">
      <!-- 状态卡片 -->
      <el-row :gutter="20" class="status-cards-row">
        <el-col :span="8">
          <el-card class="status-card primary-card">
            <div class="card-content">
              <div class="card-info">
                <p class="card-label">共借阅</p>
                <h3 class="card-value">{{ mapCount.allCount || 0 }} 本</h3>
              </div>
              <div class="card-icon">
                <i class="el-icon-book"></i>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="status-card warning-card">
            <div class="card-content">
              <div class="card-info">
                <p class="card-label">借阅中</p>
                <h3 class="card-value">{{ mapCount.startCount || 0 }} 本</h3>
              </div>
              <div class="card-icon">
                <i class="el-icon-calendar"></i>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="status-card purple-card">
            <div class="card-content">
              <div class="card-info">
                <p class="card-label">已归还</p>
                <h3 class="card-value">{{ mapCount.endCount || 0 }} 本</h3>
              </div>
              <div class="card-icon">
                <i class="el-icon-heart"></i>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索区 -->
      <el-row :gutter="20" class="search-card">
        <el-col :span="24">
          <el-input v-model="name" placeholder="输入图书名称搜索" prefix-icon="el-icon-search" clearable @keyup.enter.native="handleSearch">
            <el-button slot="append" icon="el-icon-search" type="primary" @click="handleSearch"></el-button>
          </el-input>
        </el-col>
      </el-row>

      <!-- 借阅列表区 -->
      <div class="list-header">
        <h3>我的借阅列表</h3>
        <span class="count-info">共借阅 {{ tableData.length }} 本图书</span>
      </div>

      <!-- 图书网格 -->
      <div class="book-grid" v-if="tableData.length > 0">
        <el-card class="book-item" shadow="hover" v-for="borrow in tableData" :key="borrow.id">
          <div class="book-cover-container">
            <el-image :src="borrow.book.cover || defaultCover" :preview-src-list="[borrow.book.cover || defaultCover]" class="book-cover" fit="cover" @error="e => e.target.src = defaultCover"></el-image>
            <el-tag class="status-tag" :type="borrow.state === '借阅中' ? 'success' : 'info'">
              {{ borrow.state }}
            </el-tag>
          </div>
          <div class="book-info">
            <h4 class="book-title">
              <el-tooltip effect="dark" :content="borrow.name" placement="top">
                <el-button type="text" style="color: #666666;font-size: 14px" @click="handleViewDetail(borrow.book)">
                  {{ borrow.name }}
                </el-button>
              </el-tooltip>
            </h4>
            <p class="book-author">作者：{{ borrow.book.author || '未知' }}</p>
            <p class="book-category">分类：{{ getCategoryName(borrow.book.categoryId) }}</p>
            <p class="book-isbn">ISBN：{{ borrow.book.isbn || '未知' }}</p>
            <div class="book-actions">
              <el-button
                  size="mini"
                  type="text"
                  @click="goPage('/front/bookDetail?id=' + borrow.book.id)"
              >
                详情
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 空状态 -->
      <div v-else>
        <el-empty
            :image-size="300"
            :image="require('@/assets/empty.svg')"
            description="暂无借阅，请您先借阅图书奥~~"
        ></el-empty>
      </div>
    </div>

    <!-- 图书详情弹窗 -->
    <el-dialog
        title="图书详情"
        :visible.sync="detailDialogVisible"
        width="700px"
        :close-on-click-modal="false"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-image :src="currentBook.cover || defaultCover" class="detail-cover" fit="cover" @error="e => e.target.src = defaultCover"></el-image>
        </el-col>
        <el-col :span="18">
          <el-descriptions column="1" border>
            <el-descriptions-item label="图书名称">{{ currentBook.name || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="作者">{{ currentBook.author || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="出版社">{{ currentBook.publisher || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="出版日期">{{ currentBook.date || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="ISBN">{{ currentBook.isbn || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="分类">{{ getCategoryName(currentBook.categoryId) }}</el-descriptions-item>
            <el-descriptions-item label="库存">{{ currentBook.store || 0 }} 本</el-descriptions-item>
            <el-descriptions-item label="简介" :contentStyle="{ whiteSpace: 'normal', lineHeight: '1.6' }">
              {{ currentBook.descr || '暂无简介' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BookBorrowSystem',
  data() {
    return {
      // 基础配置
      defaultCover: require('@/assets/logo.svg'), // 默认封面图
      // 搜索参数
      name: '',
      // 数据列表
      tableData: [],
      mapCount: {},
      categories: [],
      user: JSON.parse(localStorage.getItem("user") || '{}'),

      // 弹窗相关
      detailDialogVisible: false,
      currentBook: {}
    }
  },
  created() {
    this.checkLogin();
    this.loadData();
  },
  methods: {
    // 检查登录状态
    checkLogin() {
      if (!this.user.name) {
        this.$notify.warning({ title: '提示', message: '请先登录', duration: 2000 });
        this.$router.push('/login');
      }
    },

    // 加载所有数据
    loadData() {
      if (!this.user.name) return;

      // 并行请求提升性能
      Promise.all([
        this.loadBorrowList(),
        this.loadBorrowCount(),
        this.loadCategories()
      ]).catch(err => {
        console.error('数据加载失败:', err);
        this.$notify.error({ title: '错误', message: '数据加载失败' });
      });
    },

    // 加载借阅列表
    loadBorrowList() {
      return this.$request.get("/borrow/page/front", {
        params: {
          pageNum: 1,
          pageSize: 8,
          name: this.name
        }
      }).then(res => {
        this.tableData = res.data?.records || [];
      });
    },

    // 加载借阅统计
    loadBorrowCount() {
      return this.$request.get("/borrow/borrowCount").then(res => {
        this.mapCount = res.data || {};
      });
    },

    // 加载分类列表
    loadCategories() {
      return this.$request.get("/category").then(res => {
        this.categories = res.data || [];
      });
    },

    // 搜索处理
    handleSearch() {
      this.loadBorrowList();
    },

    // 查看图书详情
    handleViewDetail(book) {
      this.currentBook = { ...book };
      this.detailDialogVisible = true;
    },

    // 跳转页面
    goPage(path) {
      this.$router.push(path);
    },

    // 获取分类名称
    getCategoryName(categoryId) {
      return this.categories.find(v => v.id === categoryId)?.name || '未知分类';
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.book-borrow-system {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 主体内容 */
.main-content {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  flex: 1;
}

/* 搜索区 */
.search-card {
  margin-bottom: 20px;
}

/* 列表头部 */
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.list-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}
.count-info {
  color: #606266;
  font-size: 13px;
}

/* 图书网格布局 */
.book-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}
.book-item {
  transition: all 0.3s ease;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.book-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

/* 图书封面 */
.book-cover-container {
  position: relative;
  height: 220px;
  overflow: hidden;
}
.book-cover {
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease;
}
.book-item:hover .book-cover {
  transform: scale(1.05);
}
.status-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
}

/* 图书信息 */
.book-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.book-title {
  font-size: 15px;
  font-weight: 500;
  margin: 0 0 10px;
  cursor: pointer;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.book-title:hover {
  color: #409eff;
}
.book-author, .book-category, .book-isbn {
  font-size: 12px;
  color: #606266;
  margin: 5px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.book-actions {
  margin-top: auto;
  padding-top: 10px;
}

/* 详情弹窗 */
.detail-cover {
  width: 100%;
  height: 280px;
  border-radius: 4px;
}

/* 状态卡片样式 */
.status-cards-row {
  margin-bottom: 30px;
}
.status-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.status-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}
.primary-card {
  border-left: 4px solid #3B82F6;
}
.warning-card {
  border-left: 4px solid #E6A23C;
}
.purple-card {
  border-left: 4px solid #9C27B0;
}
.card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}
.card-info {
  flex: 1;
}
.card-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}
.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}
.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}
.primary-card .card-icon {
  background-color: rgba(59, 130, 246, 0.1);
  color: #3B82F6;
}
.warning-card .card-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}
.purple-card .card-icon {
  background-color: rgba(156, 39, 176, 0.1);
  color: #9C27B0;
}
</style>
